package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.entity.YddUser;
import com.itheima.ydd.service.IYddUserService;
import com.itheima.ydd.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/home/index")
public class LoginController {

    @Autowired
    private IYddUserService yddUserService;

    @PostMapping("/login")
    public ResultData login(@RequestBody YddUser yddUser){

        LambdaQueryWrapper<YddUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YddUser::getMobile,yddUser.getMobile());
        wrapper.eq(YddUser::getPassword, DigestUtils.md5DigestAsHex(yddUser.getPassword().getBytes()));
        YddUser user = yddUserService.getOne(wrapper);

        if(user != null){
            Map<String, Object> tokenMap = new HashMap<>();
            tokenMap.put("userId", user.getId());
            String token = JwtUtils.getToken(tokenMap);
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            return ResultData.ok("",map);
        }

        return ResultData.error("手机号或密码有误!");

    }
}
